import datetime
import os
import random
import uuid

from django.core.paginator import Paginator
from django.shortcuts import render, redirect

# Create your views here.
from django.template import loader
from rest_framework.response import Response
from rest_framework.views import APIView

from approve.models import ApprHistory
from bills.models import Outbound, Transport, Enter, Bills
from bills.serializer import OutboundSerializer, BillsSerializer, TransportSerializer, EnterSerializer
from jiuyun.settings import BASE_DIR
from order.models import Indent
from transport.models import Logistics, Logdet
from user.models import Staff, Inform
from utils.decorator_ import PermissionCheck


class BillsView(APIView):
    @PermissionCheck('bills.view_outbound')
    def get(self, request, format=None):
        # 后续添加权限验证（总经理，仓库经理）可查看所有，其他职工只能查看自己相关的单据
        page = int(request.GET.get('page', '1'))
        size = int(request.GET.get('size', '20'))
        staff_id = request.user.staff_id
        staff = Staff.objects.get(pk=staff_id)
        if staff.role.role_id in ['4a1286cefec64c74a39b7fa18a0a6848', '4c2a53b3843e49ebadc4eb56b6f7e86b']:
            data = Bills.objects.all()
        else:
            data = Bills.objects.filter(staff_num=staff.num)
        paginator = Paginator(data, size)
        pager = paginator.page(page)
        # 模型实例化
        approve = BillsSerializer(pager.object_list, many=True)
        return Response({
            'data': approve.data,
            'total': paginator.count,
            'page': pager.number,  # page当前页号
            'pageSize': size,
            'pages': paginator.num_pages  # 总页数
        })

    @PermissionCheck('bills.add_outbound')
    def post(self, request, format=None):
        anum = request.data.get('num')
        ware_id = request.data.get('ware')
        count = request.data.get('count')
        goods_id = request.data.get('goods')
        indent_id = request.data.get('indent')
        all_st = Staff.objects.filter(role_id='4f3a5a6f63ff4606ac3d8bbb62d51997')
        index = random.randint(0, len(all_st) - 1)
        tran_st = all_st[index]
        apprs = ApprHistory.objects.filter(num=anum)
        if Inform.objects.all():
            ret = str(Inform.objects.count() + 1)
            inum = 'I' + ret.rjust(9, '0')
        else:
            inum = 'I' + '1'.rjust(9, '0')
        tran_id = uuid.uuid4().hex
        logis_id = uuid.uuid4().hex
        appr_his = None
        if apprs.exists():
            appr_his = apprs.first()
        for appr in apprs:
            if appr.appr_idea != '同意':
                return Response({'msg': '请先通过审批后在获取单据'})
        if apprs.first().appr_kind == '出库':
            # 出库类型 生成出库单和配送单
            Outbound.objects.create(out_id=uuid.uuid4().hex,
                                    num=appr_his.num,
                                    goods_id=goods_id,
                                    count=count,
                                    ware_id=ware_id,
                                    type=appr_his.appr_kind,
                                    out_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                    staff_name=Staff.objects.get(pk=appr_his.staff_id).name,
                                    staff_num=Staff.objects.get(pk=appr_his.staff_id).num)
            Bills.objects.create(bills_id=uuid.uuid4().hex, num=appr_his.num, type='出库单',
                                 bills_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                 staff_name=Staff.objects.get(pk=appr_his.staff_id).name,
                                 staff_num=Staff.objects.get(pk=appr_his.staff_id).num)
            Bills.objects.create(bills_id=uuid.uuid4().hex, num=appr_his.num, type='配送单',
                                 bills_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                 staff_name=tran_st.name, staff_num=tran_st.num)
            Transport.objects.create(transport_id=tran_id,
                                     num=appr_his.num,
                                     goods_id=goods_id,
                                     count=count,
                                     company=Indent.objects.get(indent_id=indent_id).company,
                                     transport_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                     staff_name=tran_st.name,
                                     staff_num=tran_st.num,
                                     signer=Indent.objects.get(indent_id=indent_id).sign_name,
                                     address=Indent.objects.get(indent_id=indent_id).address)
            # 生成物流单
            Logistics.objects.create(log_id=logis_id,
                                     indent_id=indent_id,
                                     transport_id=tran_id,
                                     status='等待配送')
            Logdet.objects.create(logdet_id=uuid.uuid4().hex,
                                  log_id=logis_id,
                                  status='等待配送')
            Inform.objects.create(inform_id=uuid.uuid4().hex,
                                  num=inum,
                                  staff_name=tran_st.name,
                                  staff_num=tran_st.num,
                                  time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                  event='新的配送单，请尽快配送',
                                  status='未读')
        else:
            # 入库类型 生成入库单
            Enter.objects.create(enter_id=uuid.uuid4().hex,
                                 num=appr_his.num,
                                 goods_id=goods_id,
                                 count=count,
                                 ware_id=ware_id,
                                 type=appr_his.appr_kind,
                                 enter_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                 staff_name=Staff.objects.get(pk=appr_his.staff_id).name,
                                 staff_num=Staff.objects.get(pk=appr_his.staff_id).num)
            Bills.objects.create(bills_id=uuid.uuid4().hex, num=appr_his.num, type='入库单',
                                 bills_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                 staff_name=Staff.objects.get(pk=appr_his.staff_id).name,
                                 staff_num=Staff.objects.get(pk=appr_his.staff_id).num)
            Inform.objects.create(inform_id=uuid.uuid4().hex,
                                  num=inum,
                                  staff_name=Staff.objects.get(pk=appr_his.staff_id).name,
                                  staff_num=Staff.objects.get(pk=appr_his.staff_id).num,
                                  time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                  event='有新的货品需要入库，请及时入库',
                                  status='未读')
        return Response({'msg': '单据生成成功'})


class BillsDetailView(APIView):
    @PermissionCheck('bills.view_outbound')
    def get(self, request, pk, format=None):
        bill = Bills.objects.get(pk=pk)
        if bill.type == '出库单':
            data = OutboundSerializer(Outbound.objects.get(num=bill.num), many=False)
        elif bill.type == '配送单':
            data = TransportSerializer(Transport.objects.get(num=bill.num), many=False)
        elif bill.type == '入库单':
            data = EnterSerializer(Enter.objects.get(num=bill.num), many=False)
        else:
            return Response({'msg': '未找到该单据'})
        return Response({'data': data.data})

class BillsimgView(APIView):
    def get(self,request,pk,format=None):
        bill = Bills.objects.get(pk=pk)
        if bill.type == '入库单':
            enter = Enter.objects.get(num=bill.num)
            price = int(enter.goods.retail * 0.8 * enter.count)
            dir_path = r'F:\python_code\djangoapps\jiuyun'
            img_path = r'%s\media\enter\%s.png' % (dir_path, enter.num)
            print('-->img_path', img_path)
            content = loader.render_to_string('enter.html', locals(), request)
            tmp_file_path = os.path.join(BASE_DIR, 'tmp.html')
            with open(tmp_file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            from xmlrpc.client import ServerProxy
            sp = ServerProxy('http://localhost:9800')
            sp.save_image(tmp_file_path, img_path)

            return redirect(f'/media/enter/{enter.num}.png')
        elif bill.type == '出库单':
            outbound = Outbound.objects.get(num=bill.num)
            price = int(outbound.goods.retail * 0.8 * outbound.count)
            dir_path = r'F:\python_code\djangoapps\jiuyun'
            img_path = r'%s\media\outbound\%s.png' % (dir_path, outbound.num)
            print('-->img_path', img_path)

            content = loader.render_to_string('outbound.html', locals(), request)
            tmp_file_path = os.path.join(BASE_DIR, 'tmp.html')
            with open(tmp_file_path, 'w', encoding='utf-8') as f:
                f.write(content)

            from xmlrpc.client import ServerProxy
            sp = ServerProxy('http://localhost:9800')
            sp.save_image(tmp_file_path, img_path)

            return redirect(f'/media/outbound/{outbound.num}.png')
        else:
            transport = Transport.objects.get(num=bill.num)
            price = int(transport.goods.retail * 0.8 * transport.count)

            dir_path = r'F:\python_code\djangoapps\jiuyun'
            img_path = r'%s\media\transport\%s.png' % (dir_path, transport.num)
            print('-->img_path', img_path)

            content = loader.render_to_string('transport.html', locals(), request)
            tmp_file_path = os.path.join(BASE_DIR, 'tmp.html')
            with open(tmp_file_path, 'w', encoding='utf-8') as f:
                f.write(content)

            from xmlrpc.client import ServerProxy
            sp = ServerProxy('http://localhost:9800')
            sp.save_image(tmp_file_path, img_path)

            return redirect(f'/media/transport/{transport.num}.png')